package liuliu.throughwaring.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import net.tsz.afinal.annotation.view.CodeNote;

import java.util.ArrayList;
import java.util.List;

import liuliu.custom.control.dialog.LLDialog;
import liuliu.custom.control.listview.TotalListView;
import liuliu.custom.control.toolbar.TToolbar;
import liuliu.custom.method.Utils;
import liuliu.custom.model.CodeModel;
import liuliu.throughwaring.R;
import liuliu.throughwaring.adapter.CommonAdapter;
import liuliu.throughwaring.adapter.ViewHolder;
import liuliu.throughwaring.base.BaseActivity;
import liuliu.throughwaring.control.add.police.person.IRegPersonView;
import liuliu.throughwaring.control.add.police.person.RegPersonListener;
import liuliu.throughwaring.model.CompanyModel;
import liuliu.throughwaring.model.PersonModel;

/**
 * 公司详细信息界面
 * Created by Administrator on 2016/4/28.
 */
public class CompanyDetailActivity extends BaseActivity implements IRegPersonView {
    @CodeNote(id = R.id.company_bg_iv)
    ImageView company_bg_iv;
    @CodeNote(id = R.id.tel_tv)
    TextView tel_tv;
    @CodeNote(id = R.id.address_tv)
    TextView address_tv;
    @CodeNote(id = R.id.xiangqing_btn, click = "onClick")
    Button xiangqing_btn;
    @CodeNote(id = R.id.call_btn, click = "onClick")
    Button call_btn;
    @CodeNote(id = R.id.person_cha_btn, click = "onClick")
    Button person_cha_btn;
    @CodeNote(id = R.id.add_btn, click = "onClick")
    Button add_btn;
    @CodeNote(id = R.id.renshu_tv)
    TextView renshu_tv;
    @CodeNote(id = R.id.no_data_ll)
    LinearLayout no_data_ll;
    @CodeNote(id = R.id.person_lv)
    TotalListView person_lv;
    @CodeNote(id = R.id.main_toolbar)
    TToolbar main_toolbar;
    @CodeNote(id = R.id.total_sv)
    ScrollView total_sv;
    @CodeNote(id = R.id.company_name_tv)
    TextView company_name_tv;//单位名称
    private String mCompanyId;//传送过来的公司ID
    private List<CompanyModel> mCompanys;//公司信息
    private List<PersonModel> mPersons;//当前公司人员集合
    private CommonAdapter<PersonModel> mAdapter;
    private LLDialog llDialog;//dialog声明
    private PopupWindow bottom_pop;
    RegPersonListener mListener;
    String companyName = "";
    private String tiaojian_str = "";
    String type = "";//传递过来的企业类型
    CompanyModel myCompanyModel = new CompanyModel();
    private boolean isCompany = true;
    @CodeNote(id = R.id.zaizhi_tv, click = "onClick")
    TextView zaizhi_tv;
    @CodeNote(id = R.id.lizhi_tv, click = "onClick")
    TextView lizhi_tv;
    @CodeNote(id = R.id.quanbu_tv, click = "onClick")
    TextView quanbu_tv;


    @Override
    public void initViews() {
        setContentView(R.layout.activity_company_detail);
        mCompanyId = getIntent().getStringExtra("CompanyId");
        llDialog = new LLDialog(this);
        mListener = new RegPersonListener(this, this);
    }

    @Override
    public void initEvents() {
        main_toolbar.setLeftOnClick(new TToolbar.LeftOnClickListener() {
            @Override
            public void leftclick() {
                finish();
            }
        });
        mCompanys = finalDb.findAllByWhere(CompanyModel.class, "CompanyId='" + mCompanyId + "'");
        if (mCompanys.size() > 0) {
            myCompanyModel = mCompanys.get(0);
            companyName = myCompanyModel.getCompanyName();
            company_name_tv.setText(Utils.cutStringWithDian(companyName, 16));
            tel_tv.setText(myCompanyModel.getCompanyPhoneNumber());
            type = myCompanyModel.getCompanyType();
            address_tv.setText(myCompanyModel.getCompanyAddress());
            Bitmap bitmap = Utils.getLoacalBitmap(myCompanyModel.getCompanyOveralImageUrl());
            if (bitmap != null) {
                company_bg_iv.setImageBitmap(Utils.centerSquareScaleBitmap(bitmap, 60));
            }
            if (type.equals("Lease")) {
                main_toolbar.setLeftTitle("房屋详情");
                xiangqing_btn.setText("房屋详情");
                zaizhi_tv.setText("在住");
                lizhi_tv.setText("退租");
                if (myCompanyModel.getHMenpai() == null) {
                    myCompanyModel.setHMenpai("A座403");
                }
                address_tv.setText(myCompanyModel.getCompanyAddress() + myCompanyModel.getHMenpai());
            }
        }
        initButton(1);
    }

    private void showPopWindow(View v) {
        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.pop_search_word, null);
        final EditText danwei_et = (EditText) view.findViewById(R.id.danwei_name_et);
        final Button cha = (Button) view.findViewById(R.id.cha_btn);
        cha.setText("取消");
        danwei_et.setHint("人员姓名");
        if (tiaojian_str != null) {
            if (!tiaojian_str.equals("")) {
                danwei_et.setText(tiaojian_str);
            }
        }

        if (!danwei_et.getText().toString().trim().equals("")) {
            cha.setText("查询");
            if (danwei_et.length() > 0) {
                danwei_et.setSelection(danwei_et.length());
            }
        }
        danwei_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!danwei_et.getText().toString().equals("")) {
                    cha.setText("查询");
                } else {
                    cha.setText("取消");
                }
            }
        });
        cha.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (cha.getText().equals("查询")) {
                            tiaojian_str = danwei_et.getText().toString().trim();
                            main_toolbar.setLeftTitle("条件：" + tiaojian_str);
                            bottom_pop.dismiss();
                        } else {
                            tiaojian_str = "";
                            if (!type.equals("Lease")) {
                                main_toolbar.setLeftTitle("单位详情");
                            } else {
                                main_toolbar.setLeftTitle("房屋详情");
                            }
                            bottom_pop.dismiss();
                        }
                        loadPersons();//加载指定人员信息
                    }
                }
        );
        bottom_pop = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        bottom_pop.setAnimationStyle(R.style.pop_main_bottom_anim_style);
        bottom_pop.setFocusable(true);
        bottom_pop.setOutsideTouchable(true);
        bottom_pop.setBackgroundDrawable(new BitmapDrawable());
        bottom_pop.showAtLocation(v, Gravity.BOTTOM, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        bottom_pop.setOnDismissListener(
                new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        bottom_pop.dismiss();
                    }
                }
        );
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_btn://添加
                Intent intent = new Intent();
                intent.setClass(this, RegPersonActivity.class);
                intent.putExtra("CompanyId", myCompanyModel.getCompanyId());
                startActivityForResult(intent, 77);
                break;
            case R.id.person_cha_btn://查询
                showPopWindow(person_cha_btn);
                break;
            case R.id.call_btn://打电话
                tell();
                break;
            case R.id.xiangqing_btn://详情信息
                detail();
                break;
            case R.id.zaizhi_tv://在职按钮点击
                initButton(1);
                break;
            case R.id.lizhi_tv://离职点击
                initButton(2);
                break;
            case R.id.quanbu_tv://全部点击
                initButton(3);
                break;
        }
    }

    /**
     * 根据点击的内容加载并显示button效果
     *
     * @param num 1.在职.2.离职.3.全部
     */
    private void initButton(int num) {
        zaizhi_tv.setBackgroundResource(R.color.white);
        lizhi_tv.setBackgroundResource(R.color.white);
        quanbu_tv.setBackgroundResource(R.color.white);
        zaizhi_tv.setTextColor(getResources().getColor(R.color.mainPrimaryDark));
        lizhi_tv.setTextColor(getResources().getColor(R.color.mainPrimaryDark));
        quanbu_tv.setTextColor(getResources().getColor(R.color.mainPrimaryDark));
        switch (num) {
            case 1://在职
                zaizhi_tv.setBackgroundResource(R.mipmap.select_background);
                zaizhi_tv.setTextColor(getResources().getColor(R.color.white));
                if (type.equals("Company")) {
                    sqlType = "OnJob";
                } else {
                    sqlType = "CheckIn";
                }
                break;
            case 2://离职
                lizhi_tv.setBackgroundResource(R.mipmap.select_background);
                lizhi_tv.setTextColor(getResources().getColor(R.color.white));
                if (type.equals("Company")) {
                    sqlType = "LeaveJob";
                } else {
                    sqlType = "CheckOut";
                }
                break;
            case 3://全部
                quanbu_tv.setBackgroundResource(R.mipmap.select_background);
                quanbu_tv.setTextColor(getResources().getColor(R.color.white));
                sqlType = "";
                break;
        }
        loadPersons();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 131) {
            boolean result = data.getBooleanExtra("result", true);
            if (result) {
                mUtils.ToastShort("添加成功！");
                loadPersons();
            } else {
                mUtils.ToastShort("添加失败！");
            }
        }
    }

    //单位详情
    private void detail() {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        if (type.equals("Company")) {
            intent.setClass(this, UnitDetailActivity.class);
        } else {
            intent.setClass(this, HouseDetailActivity.class);
        }
        bundle.putSerializable("CompanyModel", myCompanyModel);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    //拨打电话
    private void tell() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + myCompanyModel.getCompanyPhoneNumber()));
        startActivity(intent);
    }

    String sqlType = "";

    /**
     * 加载人员列表信息
     */
    private void loadPersons() {
        String sql = "PersonCompanyId='" + mCompanyId + "' and PersonName like '%" + tiaojian_str + "%'";
        if (!sqlType.equals("")) {
            sql += " and PersonStatus='" + sqlType + "'";
        }
        sql += " order by PersonCreateTime desc";
        mPersons = finalDb.findAllByWhere(PersonModel.class, sql);

        switch (type) {
            case "Company"://从业单位
                renshu_tv.setText("从业人数：" + mPersons.size() + "人");
                break;
            case "Lease"://出租屋
                renshu_tv.setText("承租人数：" + mPersons.size() + "人");
                break;
        }
        if (mPersons.size() > 0) {
            mAdapter = new CommonAdapter<PersonModel>(this, mPersons, R.layout.item_congye) {
                @Override
                public void convert(final ViewHolder holder, final PersonModel model, int position) {
                    holder.setPersonImageUrl(R.id.person_iv, model.getPersonImgUrl());
                    holder.setText(R.id.name_tv, model.getPersonName());
                    //关联信息
                    holder.setText(R.id.gulian_person_sum, getGuanLianNum(model.getPersonCardId()) + "");
                    String sex = "";
                    switch (model.getPersonSex()) {
                        case "2":
                            sex = "女";
                            break;
                        default:
                            sex = "男";
                            break;
                    }
                    if (type.equals("Company")) {
                        if (model.getPersonStatus().equals("OnJob")) {
                            holder.setText(R.id.state_tv, "在职");
                        } else {
                            holder.setText(R.id.state_tv, "离职");
                            holder.setText(R.id.lizhi_btn, "详情");
                        }
                    } else {
                        if (model.getPersonStatus().equals("CheckIn")) {
                            holder.setText(R.id.state_tv, "在住");
                            holder.setText(R.id.lizhi_btn, "退租");
                        } else {
                            holder.setText(R.id.state_tv, "离店");
                            holder.setText(R.id.lizhi_btn, "详情");
                        }
                    }
                    holder.setText(R.id.sex_tv, sex);
                    List<CodeModel> mode = finalDb.findAllByWhere(CodeModel.class, "codeName='Code_Nation' and Name='" + model.getPersonNation() + "'");
                    String nation = "汉族";
                    if (!mode.isEmpty()) {
                        if (mode.size() > 0) {
                            nation = mode.get(0).getValue();
                        }
                    }
                    holder.setText(R.id.nation_tv, nation);//民族
                    holder.setText(R.id.create_time_tv, Utils.loadTime(model.getPersonCreateTime()));//创建时间
                    holder.setOnClickListener(R.id.lizhi_btn, new View.OnClickListener() {//点击离职
                        @Override
                        public void onClick(View v) {
                            if (holder.getButtonText(R.id.lizhi_btn).equals("详情")) {
                                mUtils.IntentPost(PersonDetailActivity.class, new Utils.putListener() {
                                    @Override
                                    public void put(Intent intent) {
                                        intent.putExtra("personid", model.getPersonId());
                                    }
                                });
                            } else {
                                if (type.equals("Company")) {
                                    llDialog.setMiddleMessage("确认要离职？");
                                } else {
                                    llDialog.setMiddleMessage("确认要退租？");
                                }

                                llDialog.setOnPositiveListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {//通知后台给置顶人员离职
                                        model.setCheckOutTime(Utils.getTimeString());
                                        if (type.equals("Company")) {
                                            model.setPersonStatus("LeaveJob");
                                        } else {
                                            model.setPersonStatus("CheckOut");
                                        }
                                        mListener.RegPerson(model);
                                        llDialog.dismiss();
                                    }
                                });
                                llDialog.setOnNegativeListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        llDialog.cancel();
                                    }
                                });
                                llDialog.show();
                            }
                        }
                    });
                }
            };
            person_lv.setAdapter(mAdapter);
            no_data_ll.setVisibility(View.GONE);
            person_lv.setVisibility(View.VISIBLE);
            person_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                    mUtils.IntentPost(PersonDetailActivity.class, new Utils.putListener() {
                        @Override
                        public void put(Intent intent) {
                            intent.putExtra("personid", mPersons.get(position).getPersonId());
                        }
                    });
                }
            });
            Utils.setListViewHeightBasedOnChildren(person_lv);
        } else {
            no_data_ll.setVisibility(View.VISIBLE);
            person_lv.setVisibility(View.GONE);
        }

        total_sv.smoothScrollTo(0, 20);
    }

    @Override
    public void onRegPersonResult(boolean isTrue, String personId) {
        if (isTrue) {
            mUtils.ToastShort("操作成功！");
            loadPersons();
        } else {
            mUtils.ToastShort("操作失败，请重新操作");
        }
    }

    //关联信息几条
    private int getGuanLianNum(String cardid) {
        //按企业分类
        List<PersonModel> list = finalDb.findAllByWhere(PersonModel.class, "PersonCardId='" + cardid + "'");
        List<CompanyModel> guList = new ArrayList<CompanyModel>();
        for (PersonModel p : list) {
            List<CompanyModel> clist = finalDb.findAllByWhere(CompanyModel.class, "CompanyId='" + p.getPersonCompanyId() + "'");
            if (clist.size() > 0) {
                Boolean isY = true;
                for (CompanyModel c : guList) {
                    if (c.getCompanyId().equals(clist.get(0).getCompanyId())) {
                        isY = false;
                        break;
                    }
                }
                if (isY) {
                    guList.add(clist.get(0));
                }
            }
        }
        return guList.size();
    }
}
